import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/api/model/result.dart';
import 'package:huxiaodui/components/button_item.dart';
import 'package:huxiaodui/components/gallery.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

class AlarmPush extends StatefulWidget {
  const AlarmPush({super.key});
  @override
  State<AlarmPush> createState() => _AlarmPushState();
}

class _AlarmPushState extends State<AlarmPush> {
  final List<XFile> _image = [];
  final List<XFile> _video = [];

  final ImagePicker _picker = ImagePicker();
  var contentController = TextEditingController();
  var titleController = TextEditingController();

  List<Widget> getFiles() {
    List<Widget> widgets = [];

    for (var value in _video) {
      widgets.addAll([
        Container(
          decoration: const BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: Colors.grey,
                width: 0.3,
              ),
            ),

          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              const SizedBox(width: 10),
              const Icon(Icons.video_camera_back_rounded, size: 24),
              const SizedBox(width: 10),
              Text(value.name, style: const TextStyle(fontSize: 20)),
              const SizedBox(width: 16),
              InkWell(
                onTap: () {
                  setState(() {
                    _video.remove(value);
                  });
                },
                child: const Icon(Icons.delete,size: 32),
              ),
              const SizedBox(width: 16),
            ],
          ),
        ),
        const SizedBox(height: 10)
      ]);
    }

    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('发送警报'),
      ),
      body: ListView(
        children: [
          TextField(
            textInputAction: TextInputAction.next,
            controller: titleController,
            decoration: const InputDecoration(
              prefixIcon: Icon(Icons.subject),
              hintText: "",
              labelText: "标题",
            ),
          ),
          TextField(
            maxLines: null,
            textInputAction: TextInputAction.next,
            controller: contentController,
            decoration: const InputDecoration(
              prefixIcon: Icon(Icons.text_snippet),
              hintText: "",
              labelText: "描述",
            ),
          ),
          ButtonItem(
            iconData: Icons.photo_library,
            title: "添加图片(视频)",
            onTap: () {
              showModalBottomSheet(
                context: context,
                builder: (context) => SizedBox(
                  height: 180,
                  child: Column(
                    children: [
                      GestureDetector(
                        child: ListTile(
                          leading: const Icon(Icons.camera_alt),
                          title: const Text('拍照'),
                          onTap: () async {
                            await Permission.photos.request();

                            EasyLoading.show(
                                maskType: EasyLoadingMaskType.black);
                            XFile? image = await _picker.pickImage(
                                source: ImageSource.camera, imageQuality: 100);
                            Navigator.pop(context);
                            setState(() {
                              _image.add(image!);
                            });
                            EasyLoading.dismiss();
                          },
                        ),
                      ),
                      GestureDetector(
                        child: ListTile(
                          leading: const Icon(Icons.photo_library),
                          title: const Text('选择图片'),
                          onTap: () async {
                            await Permission.camera.request();

                            EasyLoading.show(
                                maskType: EasyLoadingMaskType.black);
                            XFile? image = await _picker.pickImage(
                                source: ImageSource.gallery, imageQuality: 100);

                            EasyLoading.dismiss();
                            Navigator.pop(context);
                            setState(() {
                              _image.add(image!);
                            });
                          },
                        ),
                      ),
                      GestureDetector(
                        child: ListTile(
                          leading: const Icon(Icons.video_camera_back_sharp),
                          title: const Text('添加视频'),
                          onTap: () async {
                            await Permission.camera.request();

                            EasyLoading.show(
                                maskType: EasyLoadingMaskType.black);
                            XFile? image = await _picker.pickVideo(
                                source: ImageSource.gallery);

                            EasyLoading.dismiss();
                            Navigator.pop(context);
                            setState(() {
                              _video.add(image!);
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              );
            },
            rWidget: const Icon(Icons.add),
          ),
          Container(
            child: Column(
              children: getFiles(),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(3),
            child: GalleryComponents(
              galleryItems: _image.map((image) {
                return GalleryItem(
                  onRemove: () {
                    setState(() {
                      _image.remove(image);
                    });
                  },
                  id: image.path,
                  resource: Image.file(
                    File(image.path),
                    width: 200,
                    height: 200,
                    fit: BoxFit.cover,
                  ),
                );
              }).toList(),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: send,
        tooltip: '提交',
        child: const Text("提交"),
      ),
    );
  }

  send() async {
    if (titleController.text.isEmpty && _image.isEmpty) {
      EasyLoading.showError("请输入标题");
      return;
    }
    if (contentController.text.isEmpty && _image.isEmpty) {
      EasyLoading.showError("请输入信息");
      return;
    }
    List<dynamic> files = [];
    for (XFile val in _image) {
      files.add(await MultipartFile.fromFile(val.path));
    }
    for (XFile val in _video) {
      files.add(await MultipartFile.fromFile(val.path));
    }

    await Api.request(
      isToast: true,
      fileUpload: true,
      url: AlarmUrl.add,
      data: {
        "title": titleController.text,
        "content": contentController.text,
        "files": files,
      },
      success: (Result res) {
        Navigator.pop(context, true);
      },
    );
  }
}
